import { BrowserWindow, shell } from 'electron'
import { is } from '@electron-toolkit/utils'
import { join, } from 'path'
import BaseWindow from './components/BaseWindow'

export default class MoreFeaturesWindow extends BaseWindow {
  hideMoreFeaturesSetTimeout: NodeJS.Timeout | null = null
  //创建窗口
  create(): void {
    if (this.frame !== null && !this.frame.isDestroyed()) return
    this.frame = new BrowserWindow({
      width: 200,
      height: 200,
      show: false,
      transparent: true, // 窗口背景透明 默认值为false
      alwaysOnTop: true, // 窗口置顶 默认值为false
      autoHideMenuBar: true, // 隐藏菜单栏 默认值为false
      resizable: false, // 禁止调整窗口大小 默认值为true
      hasShadow: false, // 禁止窗口阴影 默认值为true
      skipTaskbar: true, // 隐藏任务栏 默认值为false
      webPreferences: {
        preload: join(__dirname, '../preload/index.js'),
        sandbox: false, // 禁用沙箱模式
        zoomFactor: 1.0, // 禁止缩放
      }
    })

    this.frame!.on('blur', () => { // 失去焦点时隐藏窗口
      this.hideMoreFeatures(300)
    })

    const routerPath = '/moreFeatures'
    if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
      this.frame.loadURL(process.env['ELECTRON_RENDERER_URL'] + '/#' + routerPath)
    } else {
      this.frame.loadFile(join(__dirname, '../renderer/index.html'), {
        hash: routerPath
      })
    }

    // 设置窗口打开链接的处理方式
    this.frame.webContents.setWindowOpenHandler((details) => {
      shell.openExternal(details.url)
      return { action: 'deny' }
    })
  }  

  // 显示窗口
  async showMoreFeatures () {
    if (this.hideMoreFeaturesSetTimeout) {
      clearTimeout(this.hideMoreFeaturesSetTimeout)
      this.hideMoreFeaturesSetTimeout = null
    }
    // 获取aiIconWindow的中心位置
    const aiIconWindow = this.getWindow('aiIconWindow')
    const pos = aiIconWindow.frame.getContentBounds()

    // 计算窗口位置
    const bounds = this.frame!.getContentBounds()
    
    const targetX = pos.x + Math.ceil((pos.width - bounds.width) / 2)
    const targetY = pos.y + Math.ceil((pos.height - bounds.height) / 2)

    const isVisible = this.frame!.isVisible()
    if (!isVisible) {
      this.frame!.setBounds({
        x: targetX,
        y: targetY,
        width: 200,
        height: 200
      })
    }
    this.frame!.show()
    
    // 刷新置顶窗口
    this.frame!.setAlwaysOnTop(true, 'screen-saver')
    // aiIconWindow.setNotTop()
    setTimeout(() => {
      this.frame!.setAlwaysOnTop(false)
    }, 100)
    aiIconWindow.setAsTop()
    
    this.frame?.webContents.send('show-more-features')
  }

  // 隐藏窗口
  async hideMoreFeatures (data) {
    await this.frame?.webContents.send('hide-more-features')
    this.hideMoreFeaturesSetTimeout = setTimeout(() => {
      if (this.frame) {
        this.frame.hide()
        this.frame.setAlwaysOnTop(false)
      }
    }, data)
  }
}
